/*
 * Copyright © 2018 Zhenjie Yan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lixh.sdk.base.util

import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*
import java.util.regex.Pattern

/**
 * Ipv4 address check.
 */
private val IPV4_PATTERN = Pattern.compile(
    "^(" + "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}" +
            "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])$"
)

/**
 * Check if valid IPV4 address.
 *
 * @param input the address string to check for validity.
 *
 * @return True if the input parameter is a valid IPv4 address.
 */
fun isIPv4Address(input: String): Boolean {
    return IPV4_PATTERN.matcher(input).matches()
}

/**
 * Get local Ip address.
 */
val localIPAddress: InetAddress
    get() {
        var enumeration: Enumeration<NetworkInterface>? = null
        try {
            enumeration = NetworkInterface.getNetworkInterfaces()
        } catch (e: SocketException) {
            e.printStackTrace()
        }
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                val nif = enumeration.nextElement()
                val inetAddresses = nif.inetAddresses
                if (inetAddresses != null) {
                    while (inetAddresses.hasMoreElements()) {
                        val inetAddress = inetAddresses.nextElement()
                        if (!inetAddress.isLoopbackAddress && isIPv4Address(
                                inetAddress.hostAddress ?: "127.0.0.1"
                            )
                        ) {
                            return inetAddress
                        }
                    }
                }
            }
        }
        return InetAddress.getLocalHost()
    }

